<?php
declare(strict_types=1);

namespace Modules\Admin\Service;

use HiCommon\Helper;
use HiCommon\Repository\InvoiceApplyRepository;
use HiCommon\Repository\InvoiceApplyExtendRepository;

use HiCommon\Repository\RoadRescueOrderRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\OrderCheckpointRepository;

class InvoiceService
{

	/**
	 *	获取所有的发票申请列表
	 *	hinq 2019 11 19
	 *
	 **/
	public function get_list( array $arr_search ){
		try{
			$arr_option['where'] = ['status'=>1];
			$arr_option['with'] = ['user','address','extend'];
			$arr_list = InvoiceApplyRepository::get_list( (array) $arr_option , (array) $arr_search );
			$arr_list->appends($arr_search);//添加链接参数
			$arr_list = list_page_data( $arr_list , $arr_search );
			foreach ( $arr_list['data'] as $key => &$value ){
                $kai = 0;
                $all = 0;
                foreach ( $value['extend'] as $k => $val ){
                    $all++;
                    if( $val['status'] == 2 ){
                        $kai++;
                    }
                }
                $value['kai'] = $kai;
                $value['all'] = $all;
                unset( $value['extend'] );
            }
			return hello_success('成功',$arr_list);
		}catch( \Exception $exception ){
			return ['state'=>1,'msg'=>$exception->getMessage()];
		}
	}

	/**
	 *	获取指定的发票的详细信息
	 *	hinq 2019 11 20
	 *
	 **/
	public function detail( array $arr_search ){
		try{
			//获取指定的申请信息
			// $arr_option['with'] = ['user','address','extend','extend.order','extend.order.getOrderGoods'];
			$arr_option['with'] = ['user','extend'];
			$arr_list = InvoiceApplyRepository::get_one_where( (array) ['id'=>$arr_search['id'] ] , (array) $arr_option );
			return $arr_list->toArray();
		}catch( \Exception $exception ){
			return ['state'=>1,'msg'=>$exception->getMessage()];
		}
	}


	/**
	 *	获取指定的发票关联的订单信息
	 *	hinq 2019 11 20 
	 *
	 **/
	public function goods_order( array $arr_input ){
		try{
			$nId = $arr_input['id'];
			$arr_option['where'] = ['link_id'=>$nId];
			//关联的订单类别
			$arr_option['with'] = ['order','order.shop','order_repairstore','order_repairstore.shop','order_checkpoint','order_checkpoint.shop','order_roadrescus','order_roadrescus.to_shop'];
			$arr_list = InvoiceApplyExtendRepository::get_list( (array) $arr_option )->toArray();
			$data = [];
			foreach ($arr_list['data'] as $key => $value) {
			    $str = '';
			    if( $value['type'] == 1 ){
                    $str = 'order';
                    $data[$key]['shop_name'] = $value[$str]['shop']['name'];
                    $data[$key]['goods_num'] = $value[$str]['goods_num'];
                    $data[$key]['order_no'] = $value[$str]['order_no'];
                    $data[$key]['pay_amount'] = $value[$str]['pay_amount'];
                }else if( $value['type'] == 2 ){
                    $str = 'order_repairstore';
                    $data[$key]['shop_name'] = $value[$str]['shop']['name'];
                    $data[$key]['goods_num'] = $value[$str]['goods_num'];
                    $data[$key]['order_no'] = $value[$str]['order_number'];
                    $data[$key]['pay_amount'] = $value[$str]['pay_price'];
                }else if( $value['type'] == 3 ){   //这个没测试
                    $str = 'order_checkpoint';
                    $data[$key]['shop_name'] = $value[$str]['shop']['name'];
                    $data[$key]['goods_num'] = $value[$str]['appointment_num'];
                    $data[$key]['pay_amount'] = $value[$str]['price'];
                    $data[$key]['order_no'] = $value[$str]['order_sn'];
                }else if( $value['type'] == 4 ){
			        $str = 'order_roadrescus';
			        $data[$key]['shop_name'] = $value[$str]['to_shop']['name'];
                    $data[$key]['goods_num'] = 1;
                    $data[$key]['pay_amount'] = $value[$str]['price'];
                    $data[$key]['order_no'] = $value[$str]['order_sn'];
                }
                $data[$key]['created_at'] = $value[$str]['created_at'];
                $data[$key]['remark'] = $value['remark'];
                $data[$key]['is_invoice'] = $value['status'] == 2 ? '已开发票' : '未开发票';
                $data[$key]['id'] = $value['id'];
                $data[$key]['status'] = $value['status'];
                $data[$key]['order_id'] = $value['goods_order_id'];
                $data[$key]['type'] = $value['type'];
            }
			$temp = [
	       		"code"=> 0,
				"msg"=> "",
				"count"=> $arr_list['total'],
				"data"=>$data
	       	];
			return $temp;
		}catch( \Exception $exception ){
			return ['state'=>1,'msg'=>$exception->getMessage()];
		}
	}

	/**
	 *	确认发送发票信息
	 *	hinq 2019 11 20
	 *	不管当前申请订单中包含多少个商品订单  要么都开发票失败  要么都开发票成功
	 **/
	public function check_order( array $arr_search ){
		try{
			//验证当前商品是否已经开过发票
        if( empty( $arr_search['shenqin_status'] ) ){
            return hello_error('请选择操作类型');
        }
        if( $arr_search['shenqin_status'] == 2 ){   //成功开票的时候才填写张数
            if( empty( $arr_search['num'] ) ){
                return hello_error('请输入开发票的张数');
            }
        }
        if( empty( $arr_search['content'] ) ){
            return hello_error('请输入开票的备注信息');
        }
        if( empty( $arr_search['id'] ) ){
            return hello_error('参数错误');
        }

        //根据申请的发票id获取订单数
        $arr_option['where'] = ['link_id' => $arr_search['id']];
        $extend = InvoiceApplyExtendRepository::get_all( $arr_option )->toarray();
        $goods_ids = [];  //所有的订单id集合
        $type = '';
        foreach ( $extend as $key => $vo ){
            $goods_ids[] = $vo['goods_order_id'];
            $type = $vo['type'];
        }

        \DB::beginTransaction();
            $data['id'] = (int)$arr_search['id'];
            $data['shenqin_status'] = (int)$arr_search['shenqin_status'];
            $is_invoice = 0; // 默认未开票
            if( $arr_search['shenqin_status'] == 2 ){   //开票成功
                $data['number'] = (int)$arr_search['num'];
                $is_invoice = 1;
            }
            $data['content'] = $arr_search['content'];
            $res = InvoiceApplyRepository::edit_one( (array) $data);  //修改订单信息

            $temp['is_invoice'] = $is_invoice;
            $res2 = true;
            if( $type == 1 ){           //普通订单
                //修改订单信息已开发票
                $res2 = StoreOrderRepository::edit_one_whereIn( (array) ['key'=>'id' , 'value'=> $goods_ids ], (array) $temp );
            }else if( $type == 2 ){     //服务订单
                //修改订单信息已开发票
                $res2 = OrderRepairstoreRepository::edit_one_whereIn( (array) ['key'=>'id' , 'value'=> $goods_ids ] , (array) $temp );
            }else if( $type == 3 ){     //预约订单
                //修改订单信息已开发票
                $res2 = OrderCheckpointRepository::edit_one_whereIn( (array) ['key'=>'id' , 'value'=> $goods_ids ] , (array) $temp );
            }else if( $type == 4 ){     //道路救援
                //修改订单信息已开发票
                $res2 = RoadRescueOrderRepository::edit_one_whereIn( (array) ['key'=>'id' , 'value'=> $goods_ids ] , (array) $temp );
            }
            $arr_where['link_id'] = (int) $arr_search['id'];
            $arr_data['status'] = 2;
            $arr_data['remark'] = $arr_search['content'];
            $res3 = InvoiceApplyExtendRepository::edit_where( (array) $arr_where , (array) $arr_data );  //修改订单信息
            if( $res && $res2 && $res3 ){
                \DB::commit();
                return hello_success('ok');
            }else{
                \DB::rollback();  //回滚
                return hello_error('开票失败');
            }
		}catch(\Exception $exception ){
			return ['state'=>1,'msg'=>$exception->getMessage()];
		}
	}


}